package com.lambda.lambda.wx.service;

import com.lambda.lambda.wx.domain.ConnectionParam;
import com.lambda.lambda.wx.domain.WeChatUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

/**
 * @author jichao
 * @date 2022/2/18 16:01
 */
@Service
@RequiredArgsConstructor
public class WxCheckService {

    @Value("${weChat.token}")
    private String token;

    public void checkAndDoSha1(HttpServletResponse response, ConnectionParam connectionParam) {
        String timestamp = connectionParam.getTimestamp();
        String nonce = connectionParam.getNonce();
        String signature = connectionParam.getSignature();
        String echostr = connectionParam.getEchostr();
        String[] params = {token,timestamp,nonce};
        //排序
        Arrays.sort(params);
        String src = "";
        for(String param : params){
            src += param;
        }
        //sha1加密
        String sha1String = WeChatUtil.sha1Hex(src);
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(sha1String.equals(signature)){
            //比对成功返回echostr
            out.print(echostr);
        }else{
            out.print("Connection fail");
            System.out.println("连接失败");
        }
    }
}
